import React from "react";
import { PanResponder, View, Image, TouchableOpacity } from "react-native";
import camera from "assets/images/ic_camera.png";
import styles from "./BoxStyles";

import BoxContext from "./BoxContext";

class Box extends React.Component {
  static contextType = BoxContext;

  constructor(props) {
    super(props);
    this.refContainer = React.createRef();

    const { disable } = this.props;

    this.state = {
      isMove: false,
      isInit: true,
      moveTop: 0,
      moveLeft: 0,
      position: {},
    };

    // console.log(!!children);

    if (!disable) {
      this.panResponder = PanResponder.create({
        onStartShouldSetPanResponder: () => true,
        // onStartShouldSetPanResponder: (evt, gestureState) => {
        //   // return true if user is swiping, return false if it's a single click
        //   return !(gestureState.dx === 0 && gestureState.dy === 0);
        // },
        // onMoveShouldSetPanResponder: () => false,
        onMoveShouldSetPanResponder: (evt, gestureState) => {
          // return true if user is swiping, return false if it's a single click
          // const { dx, dy, moveX, moveY } = gestureState;
          // console.log(dx, dy, moveX, moveY);
          // console.log(Math.abs(gestureState.dx), Math.abs(gestureState.dy));
          return !(
            Math.abs(gestureState.dx) < 2 && Math.abs(gestureState.dy) < 2
          );
        },
        // handleMoveShouldSetPanResponder(e, gestureState) {
        //   let x = gestureState.dx;
        //   let y = gestureState.dy;
        //   if (x != 0 && y == 0) {
        //     return true;
        //   }
        //   return false;
        // },

        onPanResponderGrant: e => {
          this._onPanResponderBegin(e);
        },
        onPanResponderMove: (e, gestureState) => {
          this._onPanResponderMove(e, gestureState);
        },
        onPanResponderEnd: (e, g) => {
          this._onPanResponderEnd(e, g);
        },
      });
    }
  }

  localOnInitPosition = layout => {
    const { onInitPosition } = this.context;

    onInitPosition(layout);
    this.setState({
      isInit: false,
      position: layout,
    });
  };

  _onPanResponderBegin(e) {
    const { children } = this.props;
    if (!children) {
      return;
    }

    // LayoutAnimation.spring();
    const { pageX, pageY, locationX, locationY } = e.nativeEvent;

    this.pageX = pageX;
    this.pageY = pageY;
    this.locationX = locationX;
    this.locationY = locationY;
  }

  _onPanResponderMove(evt, g) {
    const { children } = this.props;
    if (!children) {
      return;
    }
    const { position } = this.state;
    const { onPositionChange } = this.context;
    const { id, style } = this.props;
    const { width, height } = style;

    this.setState({
      isMove: true,
      moveTop: position.y + g.moveY - this.pageY,
      moveLeft: position.x + g.moveX - this.pageX,
    });
    onPositionChange({
      id,
      position: {
        top: position.y + g.moveY - this.pageY,
        bottom: position.y + g.moveY - this.pageY + height,
        left: position.x + g.moveX - this.pageX,
        right: position.x + g.moveX - this.pageX + width,
      },
    });
  }

  // 移动手势处理
  _onPanResponderEnd(evt, g) {
    const { children } = this.props;
    if (!children) {
      return;
    }
    const { position, isMove } = this.state;
    const { id } = this.props;

    const { interchange, onPositionChangeEnd } = this.context;

    const newState = {
      isMove: false,
      position: {
        ...position,
      },
    };
    if (isMove && !interchange) {
      newState.position.y = position.y + g.moveY - this.pageY;
      newState.position.x = position.x + g.moveX - this.pageX;
    }
    this.setState({
      ...newState,
    });

    onPositionChangeEnd({
      id,
      position: {
        ...newState.position,
      },
    });
  }

  render() {
    const { position, moveTop, moveLeft, isMove, isInit } = this.state;
    const { overlapIds } = this.context;
    const { id, children, style, disable, onClick } = this.props;
    const overlap = overlapIds.some(overlapId => overlapId === id);
    const boxStyles = {
      ...styles.root,
      ...(overlap ? styles.active : {}),
      ...style,
    };
    if (!isInit) {
      boxStyles.top = isMove ? moveTop : position.y;
      boxStyles.left = isMove ? moveLeft : position.x;
    }

    return (
      <>
        <View
          ref={this.refContainer}
          style={boxStyles}
          {...(!disable ? this.panResponder.panHandlers : {})}
          onLayout={({ nativeEvent }) => {
            const { layout } = nativeEvent;
            if (isInit) {
              this.localOnInitPosition({ id, ...layout });
            }
          }}
        >
          <TouchableOpacity
            style={{ width: style.width, height: style.height, zIndex: 2 }}
            onPress={onClick}
          >
            {children}
          </TouchableOpacity>
        </View>
        {children || overlap ? (
          <View style={{ ...style, ...styles.back }}>
            {/* <Image
              source={camera}
              style={{
                width: style.width / 2,
                height: style.height / 2,
                resizeMode: "contain",
              }}
            /> */}
          </View>
        ) : (
          <View style={{ ...style, ...styles.noContent }}>
            <Image
              source={camera}
              style={{
                width: style.width / 2,
                height: style.height / 2,
                resizeMode: "contain",
              }}
            />
          </View>
        )}
      </>
    );
  }
}

export default Box;
